/**
 * 
 */
package ar.edu.utn.frsf.cidisi.ginet.generation.pnml2wscdl;

import java.io.IOException;
import java.util.HashMap;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.pnml.tools.epnk.pnmlcoremodel.Page;
import org.w3._2005._10.cdl.CdlFactory;
import org.w3._2005._10.cdl.DocumentRoot;
import org.w3._2005._10.cdl.TChoreography;
import org.w3._2005._10.cdl.TPackage;
import org.w3._2005._10.cdl.TSequence;
import org.w3._2005._10.cdl.TVariable;
import org.w3._2005._10.cdl.TVariableDefinitions;

import ar.edu.utn.frsf.cidisi.ginet.GINet;
import ar.edu.utn.frsf.cidisi.ginet.generation.pnml2wscdl.elementstemplate.InteractionProtocolWSCDL;

/**
 * @author Neri
 * 
 */
public class GINet2WSCDL {
	
	private EList<Page> pages;
	
	private DocumentRoot documentRoot;
	
	private TPackage tpackage;
	
	public GINet2WSCDL(GINet rootElement) {
		this.documentRoot = CdlFactory.eINSTANCE.createDocumentRoot();
		this.tpackage = CdlFactory.eINSTANCE.createTPackage();
		this.pages = rootElement.getPage();
		this.documentRoot.setPackage(this.tpackage);
	}

	public void saveWSCDL(String path) {
		this.createWSCDLFile(path);
	}
	
	public void createPackageWSCDL(){
		TChoreography choreography = CdlFactory.eINSTANCE.createTChoreography();
		choreography.setIsolation(false);
		choreography.setName("interactionprotocol");
		
		InteractionProtocolWSCDL ipWscdl = new InteractionProtocolWSCDL(this.pages.get(0), choreography);
		TSequence sequence = ipWscdl.createWSCDLElement();
		choreography.setSequence(sequence);
		
		choreography.setComplete("cdl:globalizedTrigger('termination')");
		
		TVariableDefinitions varDef = CdlFactory.eINSTANCE.createTVariableDefinitions();
		
		TVariable var = CdlFactory.eINSTANCE.createTVariable();
		
		var.setName("Termination");

		varDef.getVariable().add(var);
		
		choreography.setVariableDefinitions(varDef);
		
		this.tpackage.setTargetNamespace("giNetUpcolbpip");
		
		this.tpackage.setName("giNetUpcolbpip");

		this.tpackage.getChoreography().add(choreography);
	}
	
	/**
	 * @param page
	 * @return
	 *
	 * @author Neri
	 */
	public Resource createWSCDLFile(String path) {

		// create the resource and add the net to it
		ResourceSet resourceSet = new ResourceSetImpl();

		final URI uri = URI.createURI("platform:" + path);

		final Resource newResource = resourceSet.createResource(uri);

		EList<EObject> contents = newResource.getContents();

		contents.add(this.documentRoot);

		try {

			newResource.save(new HashMap<Object, Object>());

		} catch (IOException e) {

			return null;

		}

		return newResource;

	}
}
